package com.team2.outpatient_sys.service.impl;

import com.team2.outpatient_sys.dao.DistributionDao;
import com.team2.outpatient_sys.dao.PharmacyStorageDao;
import com.team2.outpatient_sys.dao.StorageInDao;
import com.team2.outpatient_sys.dao.UnqualifiedMedicineDao;
import com.team2.outpatient_sys.pojo.*;
import com.team2.outpatient_sys.service.PharmacyInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class PharmacyInServiceImpl implements PharmacyInService {
    @Autowired
    private DistributionDao distributionDao;

    @Autowired
    private UnqualifiedMedicineDao unqualifiedMedicineDao;

    @Autowired
    private StorageInDao storageInDao;

    @Autowired
    private PharmacyStorageDao pharmacyStorageDao;


    //查询所有没接收的药品
    @Override
    public List<ShowDistribution> findAllDistribution() {
        return distributionDao.findAll();
    }
    //查询所有已经接收的药品
    @Override
    public List<ShowDistribution> findAllDistributionYes() {
        return distributionDao.findAllByDistributionState();
    }

    //查询所有已经上架的药品
    @Override
    public List<StorageInMedicine> findAllStorageInYes() {
        return storageInDao.findAllStorageInYes();
    }

    //添加入库表
    @Override
    public Integer storageIn(StorageIn storageIn,String name) {
        //根据药品id和药品状态插入接收人名字和更改接收状态为是
        Integer medicineId = storageIn.getMedicineId();
        distributionDao.updateStateAndName(medicineId,name);

        storageIn.setShelves("否");
        return storageInDao.add(storageIn);
    }
    //添加问题表
    @Override
    public Integer add(UnqualifiedMedicine unqualifiedMedicine) {
        return unqualifiedMedicineDao.add(unqualifiedMedicine);
    }
    //展示所有未上架药品
    @Override
    public List<StorageInMedicine> findAllStorageIn() {
        return storageInDao.findAllStorageIn();
    }

    //上架(向库存表中添加数据)
    @Override
    public Integer addPharmacyStorage(PharmacyStorage pharmacyStorage) {
        //更改入库表中的入库状态
        Integer medicineId = pharmacyStorage.getMedicineId();
        storageInDao.updateShelves(medicineId);

        /**
         * 在上架之前先根据名字查询数据库。
         * 判断数据库中是否有该药品，
         * 如果没有就调用新增的方法
         * 如果有则根据名字增加存量和更新日期
         * */
        PharmacyStorage byName = pharmacyStorageDao.findByName(pharmacyStorage.getName());

        if (byName == null){
            return pharmacyStorageDao.add(pharmacyStorage);
        }else{
            return pharmacyStorageDao.updateByName(pharmacyStorage);
        }
    }
}

